package com.yj.event_listener.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.yj.event_listener.interfaces.NotificationCallback;
import com.yj.event_listener.util.LogUtil;
import com.yj.event_listener.util.RemarkUtil;
import com.yj.event_listener.util.SmsUtil;

public class SmsReceiver extends BroadcastReceiver {

    private final NotificationCallback notificationCallback;

    public SmsReceiver(NotificationCallback callback) {
        this.notificationCallback = callback;
    }

    private long lastChange = 0L;
    @Override
    public void onReceive(Context context, Intent intent) {
        long current = System.currentTimeMillis();
        if(current - lastChange < 200){
            return;
        }
        lastChange = current;
        if(intent.getComponent() != null){
            LogUtil.d(intent.getComponent().toString());
            LogUtil.d(context.getPackageName());
            LogUtil.d(getClass().toString());
        }
        LogUtil.d(intent.toString());
        Bundle bundle = intent.getExtras();
        for (String key : bundle.keySet()) {
            Object value = bundle.get(key);
            LogUtil.d(key + " : " + value.toString());
        }
        SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
        for (SmsMessage message : messages){
            String address = message.getDisplayOriginatingAddress();
            String body = message.getDisplayMessageBody();
//            LogUtil.d(message.getPseudoSubject());
            LogUtil.d(address);
//            LogUtil.d(message.getOriginatingAddress());
//            LogUtil.d(message.getServiceCenterAddress());
//            LogUtil.d(message.getMessageBody());
            LogUtil.d(body);

//            // Retrieve contact ID from the phone number
//            String contactId = RemarkUtil.getContactIdFromPhoneNumber(context, message.getDisplayOriginatingAddress());
//            LogUtil.d("contactId " + contactId);
//
//            // Retrieve contact remark using contact ID
//            String remark = RemarkUtil.getContactRemarkFromId(context, contactId);
//            LogUtil.d("remark " + remark);

            String titleName = RemarkUtil.getSenderTitle(context, message.getDisplayOriginatingAddress());
            if(notificationCallback != null){
                notificationCallback.onSms(titleName == null || titleName.isEmpty() ? address : titleName, body);
            }
        }
//        SmsUtil.getFirstSMSMessage(context);
    }
}
